<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2019/1/16
 * Time: 10:06
 */
namespace app\api\controller;
use think\Db;
use think\File;
use think\Request;
class My extends Base {
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }
    }

    /*****
     * @return \think\response\Json
     *我的首页
     */
    public function info(){

        extract(input());
        $where['user_id'] = $user_id;
        $res = Db::table('up_u_user')->where($where)->field('user_image,user_username,user_all_money,user_face,user_active_money,user_super_no,user_recharge')->find();
        $sup_info = Db::table('up_super')->where('sup_user_id',$user_id)->field('sup_status,is_super,sup_auth')->find();
        $sup_status = $sup_info['sup_status'];
        $is_super = $sup_info['sup_auth'];
        if(empty($sup_status)){
            $sup_status = 4;
        }
        if(empty($sup_status)){
            $is_super = 0;
        }
        $res['sup_status'] = $sup_status;
        $res['is_super'] = $is_super;//0是正常人  1是普通达人  2是超级达人
        return json(array('status'=>200,'msg'=>$res));
    }

    public function datum(){
        extract(input());
        $where['user_id'] = $user_id;
        $res = Db::table('up_u_user')->where($where)->field('user_image,user_username,user_gender,user_birthday,user_sign')->find();
        return json(array('status'=>200,'msg'=>$res));
    }
    /**
     * uploadLocality图片上传至本地&压缩
     */
    public function uploadLocality(){
        $file = request()->file('file');
        $yasuo = false;
        if (!$file->checkSize(1024 * 1024 * 5)) { //大于5M就压缩一下
            $yasuo = true;
        }
        $dir = ROOT_PATH . 'public' . DS . 'uploads/images';
        if(!file_exists($dir)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($dir, 0700,true);
        }
        $info = $file->move($dir);
        if($info){
            $newName = $info->getSaveName();
            //压缩图片
            if ($yasuo === true) { //大于5M就压缩一下
                $this->image_png_size_add($dir . '/' . $newName, $dir . '/' . $newName);
            }
            return json(array('status'=>200,'msg'=>'http://'.$_SERVER['SERVER_NAME']."/uploads/images/{$newName}"));

//            echo "/uploads/images/{$newName}";
        }else{
//            echo $file->getError();
            return json(array('status'=>201,'msg'=>$file->getError()));
        }
    }


    /*******
     * @return \think\response\Json
     * 编辑个人信息
     */
    public function updateInfo(){
        extract(input());
        $image = input('param.image');
        $sex = input('param.sex');
        $username = input('param.username');
        $user_sign = input('param.user_sign');
        $user_birthday = input('param.user_birthday');
        if($image!=''){
            $data['user_image'] = $image;
        }
        if($sex!=''){
            $data['user_gender'] = $sex;
        }
        if($username!=''){
            $data['user_username'] = $username;
        }
        if($user_sign!=''){
            $data['user_sign'] = $user_sign;
        }
        if($user_birthday!=''){
            $data['user_birthday'] = $user_birthday;
        }
        $where['user_id'] = $user_id;
        $res = Db::table('up_u_user')->where($where)->update($data);
        if($res){
            return json(array('status'=>200,'msg'=>"修改成功"));
        }else{
            return json(array('status'=>201,'msg'=>"修改失败"));
        }
    }

    /******
     * @return \think\response\Json
     * 关注
     */
    public function follow(){
        extract(input());
        $page = input('param.page')?input('param.page'):1;
        $num = 10;
        $pageSize = $page -1;
        $where['a.follow_status'] = 1;
        $where['a.follow_user_id'] = $user_id;
        $where['us.s_sta'] = 1;
        $res = Db::table('up_follow')->alias('a')
            ->join('up_shops us','us.s_id = a.follow_s_id','left')
            ->where($where)
            ->field('a.follow_id,us.s_name,us.s_thumb,us.s_id,us.s_task_num,us.s_address')
            ->limit($pageSize*$num,$num)
            ->select();
        return json(array('status'=>200,'msg'=>$res));
    }

    /****
     * @return \think\response\Json
     * 关注 取消关注
     */
    public function cancel(){
        $follow_id = input('param.follow_id');
        $follow_status = Db::table('up_follow')->where('follow_id',$follow_id)->value('follow_status');
        if($follow_status==1){
            $data['follow_status'] = 2;
        }
        if($follow_status==2){
            $data['follow_status'] = 1;
        }
        $data['unfollow_time'] = date('Y-m-d H:i:s',time());
        $res = Db::table('up_follow')->where('follow_id',$follow_id)->update($data);
        if($res){
            return json(array('status'=>200,'msg'=>"操作成功"));
        }else{
            return json(array('status'=>200,'msg'=>"操作失败"));
        }
    }


    /*****
     * @return \think\response\Json
     * 账号明细
     * 如果md_mold为7时，status为提现状态和content拒绝原因
     */
    public function account(){
        extract(input());
        $where['md_type'] = 1;
        $where['md_uors_id'] = $user_id;
        if(isset($active) && $active){
            $where['md_active'] = $active;
        }else{
            $where['md_active'] = ['in','1,3'];
        }
        if($page == ''){
            $res = Db::table('up_money_detail md')
                ->join('up_apply a', 'md.md_aid = a.apply_id', 'left')
                ->where($where)
                ->field('md_id,md_title,md_updown,md_money,md_time,md_mold,md_aid,apply_status,apply_content,md_active')
                ->order('md_time desc')
                ->select();
        }else{
            $num = 10;
            $pageSize = $page -1;
            $res = Db::table('up_money_detail md')
                ->join('up_apply a', 'md.md_aid = a.apply_id', 'left')
                ->where($where)
                ->field('md_id,md_title,md_updown,md_money,md_time,md_mold,md_aid,apply_status,apply_content,md_active')
                ->order('md_time desc')
                ->limit($pageSize * $num, $num)
                ->select();
        }
        $my_super = 0;
        $mysuper = Db::table('up_super')->where('sup_user_id',$user_id)->value('sup_auth');
        if($mysuper){
            $my_super = $mysuper;
        }
        return json(array('status'=>200,'msg'=>$res,'my_super'=>$my_super));
    }
    //提现欲请求
    public function cashYq(){
        extract(input());
        $user =  Db::table('up_u_user')->where('user_id',$user_id)->field('user_all_money,user_face,user_active_money')->find();
        $user_all_money = $user['user_all_money'];
        $user_all_money2 = $user['user_active_money'];
        $least = Db::table('up_about_us')->where('about_id',1)->value('withdraw_price'); //代表的是人民币
        if($user['user_face'] != 2){
            return json(array('status'=>201,'msg'=>"未认证不能提现"));
        }
        if($type == 1){
            if($user_all_money < $least*10){
                return json(array('status'=>201,'msg'=>'还未达到' . $least . '元提现金额哦，赶快去做任务吧~'));
            }else{
                if($user_all_money < 8.8){
                    return json(array('status'=>201,'msg'=>'账户余额不得低于8.8，赶快去做任务吧~'));
                }else{
                    return json(array('status'=>200,'msg'=>"OK"));
                }
            }
        }else{
            $week = date('w');
            if($week != 2 && $week != 5){
                return json(array('status'=>201,'msg'=>"只有礼拜二和礼拜五才能提现"));
            }
            if($user_all_money2 < 1){
                return json(array('status'=>201,'msg'=>"还未达到0.1元提现金额哦，赶快去做任务吧~"));
            }
            return json(array('status'=>200,'msg'=>"OK"));
        }


    }
    //活动任务可以提交
    public function makesurecan(){
        extract(input());
        $user =  Db::table('up_u_user')->where('user_id',$user_id)->field('user_all_money,user_face,user_phone')->find();
        //-------------------------------
        $phone = $user['user_phone'];
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('create_time desc')
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        $create_time = strtotime($res['create_time']);
        if($now - $create_time >= 601) {
            return json(['status' => 0, 'msg' => '验证码失效']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        //-------------------------------
        return json(['status' => 200, 'msg' => 'ok']);
    }

    /**
     * 获取提现费率
     * @return \think\response\Json
     */
    public function getCashFeilv()
    {
        $price = Db::table('up_about_us')->where('about_id', 1)->value('cash_feilv');
        return json(array('status'=>200,'msg'=>$price));
    }
    /****
     * @return \think\response\Json
     * 提现(普通)
     */
    public function cash(){
        extract(input());
        $money = input('param.money'); //代表的是人民币
        $apply_type = input('param.apply_type');
        $apply_rel_name = input('param.apply_rel_name');
        $apply_account = input('param.apply_account');
        $user =  Db::table('up_u_user')->where('user_id',$user_id)->field('user_all_money,user_face')->find();
        $user_all_money = $user['user_all_money'];
        $least = Db::table('up_about_us')->where('about_id',1)->value('withdraw_price'); //代表的是人民币
        if($user['user_face'] != 2){
            return json(array('status'=>201,'msg'=>"未认证不能提现"));
        }
        if($money < $least){
            return json(array('status'=>201,'msg'=>"还未达到".$least."元提现金额哦，赶快去做任务吧~"));
        }
        if($money*10 > $user_all_money){
            return json(array('status'=>201,'msg'=>"账户余额不足,不能超过提现金额"));
        }
        if($user_all_money - $money*10 < 8.8){
            return json(array('status'=>201,'msg'=>"账户金币余额必须大于0.88元"));
        }
        $feilv = Db::table('up_about_us')->where('about_id',1)->value('cash_feilv'); //提现费率
        $data['apply_user_id'] = $user_id;
        $data['apply_money'] = $money;
        $data['apply_get_money'] = $money*(1000-$feilv)/1000;
        $data['apply_rel_name'] = $apply_rel_name;
        $data['apply_account'] = $apply_account;
        $data['apply_type'] = $apply_type;
        $data['applt_time'] = date('Y-m-d H:i:s',time());
        $res = Db::table('up_apply')->insertGetId($data);
        if($res){
            Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_all_money',$money*10);
            //申请成功就入明细
            allInDetail($user_id,2,'提现',$money*10,7,1,$res);
//            Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_all_money');

            return json(array('status'=>200,'msg'=>"填写成功"));
        }else{
            return json(array('status'=>300,'msg'=>"填写失败"));
        }
    }
    /****
     * @return \think\response\Json
     * 提现(活动)
     */
    public function cashActive(){
        extract(input());
        $money = input('param.money'); //代表的是人民币
        $apply_type = input('param.apply_type');
        $apply_rel_name = input('param.apply_rel_name');
        $apply_account = input('param.apply_account');
        $user =  Db::table('up_u_user')->where('user_id',$user_id)->field('user_active_money,user_face,user_phone')->find();
        $user_all_money = $user['user_active_money'];
        $feilv = Db::table('up_about_us')->where('about_id',1)->value('cash_feilv'); //提现费率
        if($user['user_face'] != 2){
            return json(array('status'=>201,'msg'=>"未认证不能提现"));
        }
        $week = date('w');
        if($week != 2 && $week != 5){
            return json(array('status'=>201,'msg'=>"只有礼拜二和礼拜五才能提现"));
        }
        if($money < 0.1){
            return json(array('status'=>201,'msg'=>"还未达到0.1元提现金额哦，赶快去做任务吧~"));
        }
        if($money*10 > $user_all_money){
            return json(array('status'=>201,'msg'=>"账户余额不足,不能超过提现金额"));
        }
        $data['apply_user_id'] = $user_id;
        $data['apply_money'] = $money;
        $data['apply_get_money'] = $money*(1000-$feilv)/1000;
        $data['apply_rel_name'] = $apply_rel_name;
        $data['apply_account'] = $apply_account;
        $data['apply_type'] = $apply_type;
        $data['apply_active'] = 2;
        $data['applt_time'] = date('Y-m-d H:i:s',time());
        $res2 = Db::table('up_apply')->insertGetId($data);
        if($res2){
            Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_active_money',$money*10);
            //申请成功就入明细
            allInDetail($user_id,2,'提现',$money*10,7,2,$res2);
            return json(array('status'=>200,'msg'=>"填写成功"));
        }else{
            return json(array('status'=>300,'msg'=>"填写失败"));
        }
    }

    /****
     * @return \think\response\Json
     * 广告发布
     */
    public function advertisement(){
        extract(input());
        $name = trim(input('param.name'));
        $phone = trim(input('param.phone'));
        $company = trim(input('param.company'));
        $where['adv_name'] = $name;
        $where['adv_phone'] = $phone;
        $where['adv_company'] = $company;
        $where['adv_user_id'] = $user_id;
        $adv_id = Db::table('up_advert')->where($where)->value('adv_id');
        if($adv_id!=''){
            return json(array('status'=>201,'msg'=>"你发布的广告已经存在"));
        }
        $data['adv_name'] = $name;
        $data['adv_phone'] = $phone;
        $data['adv_company'] = $company;
        $data['adv_time'] = date('Y-m-d H:i:s',time());
        $data['adv_user_id'] = $user_id;
        $res = Db::table('up_advert')->insertGetId($data);
        if($res){
            return json(array('status'=>200,'msg'=>"发布成功"));
        }else{
            return json(array('status'=>300,'msg'=>"发布失败"));
        }
    }
    public function darenLy(){
        extract(input());
        $data = Db::table('up_realm')->select();
        return json(array('status'=>200,'msg'=>$data));
    }
    /******
     * @return \think\response\Json
     * 申请成为达人
     */
    public function daren(){
        extract(input());
        $where['sup_user_id'] = $user_id;
        $result = Db::table('up_super')->where($where)->find();
        $user_phone = Db::table('up_u_user')->where('user_id',$user_id)->value('user_phone');
        if(!isset($is_super)){
            $is_super = 1;
        }
        if($is_super != 3){
            $data['sup_user_id'] = $user_id;
            $data['sup_name'] = trim(input('param.name'));
            $data['sup_num'] = date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);//达人编号
            $data['sup_age'] = trim(input('param.age'));
            $data['sup_high'] = trim(input('param.high'));
            $data['sup_goods'] = trim(input('param.goods'));
            $data['sup_jianjie'] = trim(input('param.brief'));
            $data['sup_image'] = input('param.image');
            $data['photo'] = input('param.photo');
            $data['sup_time'] = date('Y-m-d H:i:s',time());
            $data['sup_tz'] = input('param.sup_tz');
            $data['sup_type'] = 1;
            $data['sup_phone'] = $user_phone;
            $data['is_super'] = $is_super;
        }

        if($is_super >= 2){
            $data['is_super'] = 2;
            $data['sup_jjgs'] = $sup_jjgs;
            $data['sup_jjgslxr'] = $sup_jjgslxr;
            $data['sup_jj_phone'] = $sup_jj_phone;
            $data['sup_time'] = date('Y-m-d H:i:s',time());
        }
        if($result['sup_id']==''){
            $res = Db::table('up_super')->insertGetId($data);
        }else{
            $where1['sup_id'] = $result['sup_id'];
            $data['sup_status'] = 1;
            $res = Db::table('up_super')->where($where1)->update($data);
        }
        if($res){
            return json(array('status'=>200,'msg'=>"申请成功"));
        }else{
            return json(array('status'=>300,'msg'=>"申请失败"));
        }
    }
    /******
     * @return \think\response\Json
     * 申请成为达人
     */
    public function darenInfo(){
        extract(input());
        $where['sup_user_id'] = $user_id;
        $res = Db::table('up_super')->where($where)->find();
        return json(array('status'=>200,'msg'=>$res));

    }
    /******
     * @return \think\response\Json
     * 意见反馈
     *
     */
    public function feedback(){
        extract(input());
        $content = input('param.content');
        $data['feedback_user_id'] = $user_id;
        $data['feedback_content'] = $content;
        $data['feedback_time'] = date('Y-m-d H:i:s',time());
        $res = Db::table('up_feedback')->insertGetId($data);
        if($res){
            return json(array('status'=>200,'msg'=>"提交成功"));
        }else{
            return json(array('status'=>300,'msg'=>"提交失败"));
        }
    }
    /******
     * @return \think\response\Json
     * 关于我们
     *
     */
    public function about(){
        $res = Db::table('up_about_us')->value('about_us');
        return json(array('status'=>200,'msg'=>$res));
    }

    /***
     * @return \think\response\Json
     * 账号管理
     */
    public function management(){
        extract(input());
//        $user_id =1;
        $where['user_id'] = $user_id;
        $info = Db::table('up_u_user')->where($where)->field('user_wx_token,user_qq_token,user_wb_token,user_zfb_token,user_phone')->find();
        if($info['user_wx_token']!=''){
            $res['wx_status'] = 1;
        }else{
            $res['wx_status'] = 2;
        }
        if($info['user_qq_token']!=''){
            $res['qq_status'] = 1;
        }else{
            $res['qq_status'] = 2;
        }
        if($info['user_wb_token']!=''){
            $res['wb_status'] = 1;
        }else{
            $res['wb_status'] = 2;
        }
        if($info['user_zfb_token']!=''){
            $res['zfb_status'] = 1;
        }else{
            $res['zfb_status'] = 2;
        }
        if($info['user_phone']!=''){
            $res['phone_status'] = 1;
        }else{
            $res['phone_status'] = 2;
        }
        return json(array('status'=>200,'msg'=>$res));
    }

    /******
     * @return \think\response\Json
     * 绑定第3方
     * thirdToken  第三方token
     * name  第三方昵称
     * image  第三方头像
     * type  第三方类型   1 微信  2 qq  3 微博  4 支付宝  5 手机号
     * phone  手机号  type为5时，传此值
     * code   type为5时，传此值
     */
    public function binding(){
        $user_id = input('user_id');
        $type = input('type'); // 类型  1微信  2 qq  3 微博  4 支付宝  5 支付宝
        
        if($type != 5){ // 绑定第三方
            $thirdToken = input('thirdToken');  // 第三方token
            $name = input('name');
            $image = input('image');
            if($type == 1) {
                $field = '_wx_';
            } elseif($type == 2) {
                $field = '_qq_';
            } elseif($type == 3) {
                $field = '_wb_';
            } else {
                $field = '_zfb_';
            }
            $where["user{$field}token"] = $thirdToken;
            $str = 'user_id,' . 'user' . $field . 'token,user' . $field . 'nickname,user' . $field . 'image';
            $isHave = Db::table('up_u_user')
                ->where($where)
                ->field($str)
                ->find();
            if($isHave){ // 如果被绑定的账号已存在，则走账号冲突流程
                return json(['status' => 210, 'msg' => $isHave]);
            }else{
                $update = [
                    'user' . $field . 'token' => $thirdToken,
                    'user' . $field . 'nickname' => $name,
                    'user' . $field . 'image' => $image,
                ];
                $res = Db::table('up_u_user')->where('user_id', $user_id)->update($update);
                if($res){
                    $user_info = Db::table('up_u_user')->where('user_id', $user_id)->find();
                    return json(['status' => 200, 'msg' => $user_info]);
                }else{
                    return json(['status' => 0, 'msg' => []]);
                }
            }
        }else{ // 绑定手机号
            $phone = trim(input('phone'), ' ');
            $code = trim(input('code'), ' ');
            if($code == '' || $phone == '') {
                return json(['status' => 0, 'msg' => '有未填项，请检查']);
            }
//            if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
//                return json(['status' => 0, 'msg' => '请填写正确的手机号码']);
//            }
            $isHave = Db::table('up_u_user')
                ->where('user_phone', $phone)
                ->field('user_id, user_image, user_phone')
                ->find();
            if($isHave){ // 如果被绑定的账号已存在，则走账号冲突流程
                return json(['status' => 210, 'msg' => $isHave]);
            }else{
                $res = Db::table('up_phonecode')
                    ->where('phone', $phone)
                    ->order('create_time desc')
                    ->limit(1)
                    ->find();
                if($code != $res['code']) {
                    return json(['status' => 0, 'msg' => '验证码错误']);
                }
                $now = time();
                $create_time = strtotime($res['create_time']);
                if($now - $create_time >= 601) {
                    return json(['status' => 0, 'msg' => '验证码失效']);
                }
                if($res['status'] == 1) {
                    return json(['status' => 0, 'msg' => '验证码已使用']);
                }
//                $token = md5(date('YmdHis') . rand(100000, 999999));
                $send_coin = Db::table('up_about_us')->where('about_id',3)->value('super_time');
                $update = [
//                    'user_token' => $token,
                    'user_phone' => $phone,
                    'user_china' => input('ex')
//                    'last_login_time' => date('Y-m-d H:i:s')
                ];
                $res1 = Db::table('up_u_user')->where('user_id', $user_id)->update($update);//更新用户信息
                if($res1) {
                    Db::table('up_u_user')->where('user_id', $user_id)->setInc('user_recharge',$send_coin);//更新用户信息
                    allInDetail($user_id,1,'绑定手机号送云币',$send_coin,10);
                    $userData = Db::table('up_u_user')->where('user_id', $user_id)->find();
                    Db::table('up_phonecode')->where('id', $res['id'])->update(['status' => 1]);//改变验证码状态
                    return json(['status' => 200, 'msg' => $userData]);
                } else {
                    return json(['status' => 0, 'msg' => '绑定失败']);
                }
            }
        }
    }

    /****
     * @return \think\response\Json
     * 解除绑定
     */
    public function relieve(){
        extract(input());
        //======== 判断解绑的是不是最后一种绑定类型账号
        $wx_num = 0;
        $qq_num = 0;
        $wb_num = 0;
        $zfb_num = 0;
        $phone_num = 0;
        $user_info = Db::table('up_u_user')
            ->field('user_phone, user_wx_token, user_qq_token, user_wb_token, user_zfb_token')
            ->where('user_id', $user_id)
            ->find();
        if($user_info['user_phone']){
            $phone_num = 1;
        }
        if($user_info['user_wx_token']){
            $wx_num = 1;
        }
        if($user_info['user_qq_token']){
            $qq_num = 1;
        }
        if($user_info['user_wb_token']){
            $wb_num = 1;
        }
        if($user_info['user_zfb_token']){
            $zfb_num = 1;
        }
        $total = $wx_num + $qq_num + $wb_num + $zfb_num + $phone_num;
        if($total == 1){
            return json(['status' => 0, 'msg' => '只剩一种类型账号，不可解绑']);
        }
        
        $type = input('param.type');
        if($type == 1) {
            $field = '_wx_';
        } elseif($type == 2) {
            $field = '_qq_';
        } elseif($type == 3) {
            $field = '_wb_';
        } else{
            $field = '_zfb_';
        }
        if($type != 5){
            $update = [
                'user' . $field . 'token' => '',
                'user' . $field . 'nickname' => '',
                'user' . $field . 'image' => '',
            ];
        }else{
            $update = [
                'user_phone' => '',
            ];
        }
        
        $res = Db::table('up_u_user')->where('user_id',$user_id)->update($update);
        if($res){
            return json(array('status'=>200,'msg'=>"解除绑定成功"));
        }else{
            return json(array('status'=>300,'msg'=>"解除绑定失败"));
        }
    }
//-------人脸识别-------***************************************-------------------------
    public function userFaceStatus()
    {
        extract(input());
        $user = Db::table('up_u_user')->where('user_id',$user_id)->field('user_face,user_face_idcard,user_face_name,user_all_money')->find();
        if($user['user_face'] == 3){
            return json(array('status'=>100,'msg'=>"您已在H5端提交审核了，请等待审核结果！"));
        }
        if(!$user['user_face_idcard'] || !$user['user_face_name']){
            if($user['user_all_money'] < 10){
                return json(array('status'=>100,'msg'=>"金币不足，首次提现公安部收取认证费用1元（10云币）第二次提现无需再收取，仅认证首次"));
            }
            return json(array('status'=>200,'msg'=>"还未填写信息"));
        }else{
            if($user['user_face'] == 1){
                if($user['user_all_money'] < 10){
                    return json(array('status'=>100,'msg'=>"金币不足，首次提现公安部收取认证费用1元（10云币）第二次提现无需再收取，仅认证首次"));
                }
                return json(array('status'=>200,'msg'=>"认证失败"));
            }else{
                $uname = $user['user_face_name'];
                $ucard = $user['user_face_idcard'];
                $a = mb_substr( $uname, 0, 1,'utf-8' );
                $b = mb_substr( $uname, -1, 1,'utf-8' );
                $a2 = mb_substr( $ucard, 0, 3,'utf-8' );
                $b2 = mb_substr( $ucard, -2, 2,'utf-8' );
                $showname = $a . '*' . $b;
                if(count($uname) <= 2){
                    $showname = $a . '*';
                }
                $showcard = $a2 . '*************' . $b2;
                return json(array('status'=>1000,'msg'=>"已经认证过了",'showname'=>$showname,'showcard'=>$showcard));
            }
        }
    }
    public function userFaceStatusUpdate()
    {
        extract(input());
        $res = Db::table('up_u_user')->where('user_id',$user_id)->setField('user_face',2);
        if($res){
            return json(array('status'=>200,'msg'=>"更改成功"));
        }else{
            return json(array('status'=>100,'msg'=>"更改失败"));
        }
    }
    /**
     * 获取人脸识别的biztoken
     * @return \think\response\Json
     */
    public function getbiztoken(){
        extract(input());
        $can = $this->is_idcard("$idcard");
        if($can){
            $res = Db::table('up_u_user')->where('user_id',$user_id)->update(['user_face_idcard'=>$idcard,'user_face_name'=>$idname,'user_update_time'=>date('Y-m-d H:i:s')]);
            if($res){
                $mymm = Db::table('up_u_user')->where('user_id',$user_id)->value('user_all_money');
                if($mymm < 10){
                    return json(array('status'=>100,'msg'=>"金币不足"));
                }
                $have = Db::table('up_u_user')->where('user_id','not in',$user_id)
                    ->where('user_face_idcard',$idcard)
                    ->where('user_face',2)
                    ->find();
                if($have){
                    return json(array('status'=>100,'msg'=>"已经有此认证的身份证号码了"));
                }
                $myhaver = Db::table('up_u_user')->where('user_id',$user_id)->value('user_face');
                if($myhaver == 2){
                    return json(array('status'=>100,'msg'=>"已经认证过了"));
                }
                if($myhaver == 3){
                    return json(array('status'=>100,'msg'=>"您已在H5端提交审核了，请等待审核结果！"));
                }
                //1、减钱
                Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_all_money',10);
                //2、入明细
                allInDetail($user_id,2,'认证费用',10,8);
                $signs = $this->gen_sign('YkoAcLiBbauLVXz2nqvQuGt5rcLkaaqI', 'pQFtVcuWUs_zxVFp-J9AENVE138wQHSF', 0);
//                $signs = $this->gen_sign('eTo3MEEYiP72FW9Ic_0Chrtem1L89VHK', 'QcY7x4tNgvw5S_tgWUO78NwdFr_yxACN', 0);
                $body_json = array(
                    "sign"=> $signs,
                    "sign_version"=> "hmac_sha1",
                    "liveness_type"=> "meglive",
                    "comparison_type"=> "1",
                    "idcard_name"=> "$idname",
                    "idcard_number"=> "$idcard"
                );
                $body = json_encode($body_json);
                $header = array(
                    'Accept:application/json',
                    'Content-Type:application/json;charset=utf-8'
                );
                $url = 'https://openapi.faceid.com/face/v1.2/sdk/get_biz_token';
//                $url = 'https://api.megvii.com/faceid/v3/sdk/get_biz_token ';
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                $result = curl_exec($ch);
                curl_close($ch);
                $res = json_decode($result, true);
                return json(array('status'=>200,'msg'=>$res['biz_token']));
            }else{
                return json(array('status'=>100,'msg'=>"更改失败"));
            }
        }else{
            return json(array('status'=>100,'msg'=>"请填写正确的身份证号"));
        }
    }
    protected function gen_sign($apiKey, $apiSecret, $expired){
        $rdm = rand();
        $current_time = time();
        $expired_time = $current_time + $expired;
        $srcStr = "a=%s&b=%d&c=%d&d=%d";
        $srcStr = sprintf($srcStr, $apiKey, $expired_time, $current_time, $rdm);
        $sign = base64_encode(hash_hmac('SHA1', $srcStr, $apiSecret, true).$srcStr);
        return $sign;
    }

    function is_idcard( $id )
    {
        $id = strtoupper($id);
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        $arr_split = array();
        if(!preg_match($regx, $id))
        {
            return FALSE;
        }
        if(15==strlen($id)) //检查15位
        {
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

            @preg_match($regx, $id, $arr_split);
            //检查生日日期是否正确
            $dtm_birth = "19".$arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth))
            {
                return FALSE;
            } else {
                return TRUE;
            }
        }
        else      //检查18位
        {
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            @preg_match($regx, $id, $arr_split);
            $dtm_birth = $arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth)) //检查生日日期是否正确
            {
                return FALSE;
            }
            else
            {
                //检验18位身份证的校验码是否正确。
                //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                $sign = 0;
                for ( $i = 0; $i < 17; $i++ )
                {
                    $b = (int) $id{$i};
                    $w = $arr_int[$i];
                    $sign += $b * $w;
                }
                $n = $sign % 11;
                $val_num = $arr_ch[$n];
                if ($val_num != substr($id,17, 1))
                {
                    return FALSE;
                }
                else
                {
                    return TRUE;
                }
            }
        }

    }
    /**
     * 给H5端做的认证审核——点击认证显示啥
     */
    public function faceForH5()
    {
        extract(input());
        $user = Db::table('up_u_user')->where('user_id',$user_id)
            ->field('user_face,user_h_name,user_h_idcard,user_h_zheng,user_h_fan,user_h_reason')
            ->find();
        if($user['user_face'] == 1 && !empty($user['user_h_reason'])){
            $user['user_face'] = 4;
        }
        $ucard = $user['user_h_idcard'];
        $a2 = mb_substr( $ucard, 0, 3,'utf-8' );
        $b2 = mb_substr( $ucard, -2, 2,'utf-8' );
        $user['user_h_idcard'] = $a2 . '*************' . $b2;
        //只有$user['user_face']为1和4才可以认证
        return json(array('status'=>200,'msg'=>$user));
    }
    /**
     * 给H5端做的认证审核——去认证
     */
    public function faceForH5Submit()
    {
        extract(input());
        $user = Db::table('up_u_user')->where('user_id',$user_id)
            ->field('user_face,user_h_zheng,user_h_fan,user_h_reason')
            ->find();
        if($user['user_face'] == 2 || $user['user_face'] == 3){
            return json(array('status'=>100,'msg'=>'只有未认证或认证失败的才可以提交审核'));
        }
        $data = [
            'user_face' => 3,
            'user_h_name' => $name,
            'user_h_idcard' => $idcard,
            'user_h_zheng' => $user_h_zheng,
            'user_h_fan' => $user_h_fan,
            'user_h_time' => date('Y-m-d H:i:s')
        ];
        $res = Db::table('up_u_user')->where('user_id',$user_id)->update($data);
        if($res){
            return json(array('status'=>200,'msg'=>'提交成功！'));
        }else{
            return json(array('status'=>100,'msg'=>'提交失败！'));
        }

    }
    //---------------充值--------------------------

    public function myRecharges()
    {
        extract(input());
        $jilu = Db::table('up_user_order')
            ->where('order_user_id',$user_id)
            ->where('order_status',2)
            ->order('order_paytime desc')
            ->select();
        return json(array('status'=>200,'msg'=>$jilu));
    }
    /**
     * 充值
     * @return string|\think\response\Json
     */
    public function recharge()
    {
        extract(input());
        if($money < 1){
            return json(array('status'=>100,'msg'=>'金额不能低于1元！'));
        }
        $number = time() . rand(100000,999999);
        $param = [
            'order_number' => $number,
            'order_user_id' => $user_id,
            'order_user_pay' => $money,
            'order_coin' => $money*10,
            'order_remark' => '充值',
            'order_type' => $type,//微信
            'order_time' => date('Y-m-d H:i:s')
        ];
        $res = Db::table('up_user_order')->insert($param);
        if($res){
            if($type == 1){
                $payorder = array();
                $payorder['body'] = '充值'; // 描述
                $payorder['total_fee'] = $money*100; // 订单金额
                $payorder['out_trade_no'] = $number; // 订单号
                $payorder['product_id'] = ''; // 产品ID
                $payorder['trade_type'] = 'APP'; // 类型
                $mww_weixinpay =  new \app\api\controller\Weixin();
                $respont = $mww_weixinpay->WeChatPayReady($payorder);
                return json_encode(['status'=>200,'msg'=>$respont]);
            }else{
                $mww_alipay =  new \app\api\controller\Alipay();
                $respont = $mww_alipay->getParam($number, $money, '充值', '充值');
                return json_encode($respont);
            }
        }else{
            return json(array('status'=>100,'msg'=>'订单生成失败，请刷新重试！'));
        }
    }
}